<template>
  <div class="real-name-auth-page">
    <van-nav-bar title="实名认证" left-text="返回" @click="goBack" />
    <van-uploader
      v-model="fileList"
      :after-read="handleUpload"
      :max-count="1"
      accept="image/*"
      :before-read="checkFile"
    />
    <!-- 识别结果展示 -->
    <div v-if="result" class="result-box">
      <van-cell title="姓名" :value="result.name || '未识别到姓名'" />
      <van-cell title="身份证号" :value="result.id_number || '未识别到身份证号'" />
    </div>
    <!-- 错误提示 -->
    <van-dialog v-model:show="showError" title="错误" :message="errorMessage" />

    <!-- 加载状态 -->
    <van-loading v-if="loading" vertical>识别中...</van-loading>
    
    <van-checkbox v-model="agree" />我已阅读并同意授权个人敏感信息
    <van-button type="primary" block @click="submitAuth">提交认证审核</van-button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { Toast } from 'vant';
const router = useRouter();
const fileList = ref([]);
const result = ref(null);
const loading = ref(false);
const showError = ref(false);
const errorMessage = ref('');
// 文件格式校验
const checkFile = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt4M = file.size / 1024 / 1024 < 4;
  if (!isImage) {
    Toast.fail('仅支持图片格式');
    return false;
  }
  if (!isLt4M) {
    Toast.fail('图片大小不能超过4MB');
    return false;
  }
  return true;
};

// 上传处理
const handleUpload = async (file) => {
  try {
    loading.value = true;
    const formData = new FormData();
    formData.append('file', file.file);

    const response = await axios.post(
      'http://127.0.0.1:8000/myapp/api/upload/',
      formData,
      { headers: { 'Content-Type': 'multipart/form-data' } }
    );

    // 打印完整响应，确认URL格式
    console.log('后端返回数据:', response.data);
    
    if (response.data.code === 200) {
      result.value = response.data.data;
      // Toast.success('识别成功');
      // Toast({
      //   type: 'success', // 显式声明类型
      //   message: '识别成功'
      // });
    } else {
      errorMessage.value = response.data.msg || '识别失败';
      showError.value = true;
    }
  } catch (error) {
    // 捕获并显示具体错误信息
    errorMessage.value = error.response?.data?.msg || error.message;
    showError.value = true;
  } finally {
    loading.value = false;
  }
};

const agree = ref(false);
const submitAuth = () => {
  if (agree.value) {
    // 调用接口逻辑，这里简化
    router.back();
  }
};
const goBack = () => router.back();
</script>

<style scoped>
.real-name-auth-page {
  padding: 20px;
}

.result-box {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 8px;
}
</style>